package com.code.lock;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: lwh
 * @date: Created in 2020/3/17 15:48
 * @modified By:
 */

public class SaleTicketDemo01 {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    ticket.sale();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    ticket.sale();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    ticket.sale();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

    }
}

class Ticket{

//    总票数
    private int tickets = 20;

//    synchronized本质：队列、锁
    public synchronized void sale() throws InterruptedException {
        if (tickets > 0) {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+"卖出了第"+tickets--+"张票，剩余"+tickets);
        }
    }
}